package 剑指offer;

import java.util.ArrayList;

/**
 * Created by yang on 2016/8/24.
 */
public class NumberOf1InBinary {
    public int  NumberOf1(int n) {

        // store binary number
        ArrayList<Integer> listOfBinary = new ArrayList<Integer>();
        // store 0
        ArrayList<Integer> listOf0 = new ArrayList<Integer>();
        //
        ArrayList<Integer> listOftmp = new ArrayList<Integer>();
        boolean flagNegive = false;

        if (n < 0) {
            flagNegive = true;
            if(n == Integer.MIN_VALUE) {
                return 1;
            }else{
                n = Math.abs(n);
            }
        }

        if (flagNegive) {
            while(n != 0) {
                int rem = n % 2;
//                System.out.println(~rem+2);
                listOfBinary.add(~rem+2);
                n = n / 2;
            }


        }else{
            while(n != 0) {
                int rem = n % 2;
//                System.out.println(rem);
                listOfBinary.add(rem);
                n = n / 2;
            }
        }

        // if Negtive
        if (flagNegive) {
            int sizeOflist = listOfBinary.size();
            if ( sizeOflist < 32) {
                int mission = 32 - sizeOflist;
                for (int i = 0; i < mission; i++)
                    listOf0.add(1);
                listOfBinary.addAll(listOf0);
                for(int i:listOfBinary) {
                    System.out.println(i);
                }
                System.out.println("-----------------------------");
                // +1
//                int j = 32;
                for(int i = 0;i < 32; i++) {
                    if(listOfBinary.get(i) + 1 > 1) {
                        listOftmp.add(0);
                        listOfBinary.remove(i);
                    }else{
                        listOftmp.add(1);
                        break;
                    }
                }

                listOftmp.addAll(listOfBinary);
                listOfBinary = listOftmp;
                for(int i:listOfBinary) {
                    System.out.println(i);
                }
            }
        }
        int countOf1 = 0;
        for(int i:listOfBinary) {
            if (i == 1) {
                countOf1++;
            }
        }

        return countOf1;
    }


    public void numberOf1(int n) {
        int countOf1 = 0;
        String binaryString = Integer.toBinaryString(n);
        System.out.println("binary:"+ binaryString);
        String []array = binaryString.split("");
        for(String s:array) {
            System.out.println("元素："+s);
            if("1".equals(s))
                countOf1++;
        }
        System.out.println(countOf1);
    }
}
